package com.example.nna.voz;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;

import org.jsoup.Connection.Method;
import org.jsoup.Connection.Response;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import android.graphics.Bitmap;

import com.example.nna.util.UserInfo;

public class Parser2 {
	private String m_url;
	private Document doc;
	Response res;
	private ArrayList<containPage2> ListContains;
	private UserInfo mUser;
	public String mIndexPage;
	public String Urlpage;
	public String Urlprev;
	public String Urlnext;
	public String Urlfirst;
	public String Urllast;
	public int curPage;
	public int lastPage;
	private Element mainElement;
	public Parser2(String url){
		m_url = url;
		ListContains = new ArrayList<containPage2>();
		mUser = new UserInfo();
		
	}
    public int parser(){
		try {
			if(mUser.cookies() == null){
				doc = Jsoup.connect(m_url).timeout(60000).get();
			}else{
				doc = Jsoup.connect(m_url)
						.timeout(60000)
						.cookies(mUser.cookies())
						.get();
			}
			if(doc.select("td[class*=tcat]").first().text().equals("vBulletin Message")){
				return 1;
			}else{
				mainElement = doc.select("tbody:has(form[id])").first();
				if(mainElement!= null){
					ListContains.clear();
					PaserExecute();
				}
				return 0;
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return -1;
		}
    }
    public int Subscribe(String id){
    	try {
    		res = Jsoup.connect("http://vozforums.com/subscription.php?do=addsubscription&t="+id)
					  .timeout(30000)
					  .cookies(mUser.cookies())
					  .method(Method.GET)
				      .execute();
    		
			res = Jsoup.connect("http://vozforums.com/subscription.php?do=doaddsubscription&threadid="+id)
					  .timeout(60000)
					  .cookies(mUser.cookies())
					  .method(Method.POST)
				      .execute();
			return 0;
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return -2;
		}
    }
    public int Login(UserInfo user){
    	mUser = user;
    	try {
			res = Jsoup.connect("http://vozforums.com/login.php?do=login")
					  .timeout(60000)
					  .data("do","login")
					  .data("vb_login_username",mUser.User())
					  .data("cookieuser", "1")
					  .data("vb_login_password",mUser.Pass())
					  .data("s", " ")
					  .data("securitytoken", mUser.Token())
					  .data("vb_login_md5password", mUser.md5Pass())
					  .data("vb_login_md5password_utf", mUser.md5Pass())
					  .method(Method.POST)
				      .execute();
			if(res.cookie("vfuserid") != null){
				mUser.cookies(res.cookies());
				mUser.setLogin(true); 
				return parser();
			}else return -2;	
			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return -2;
		}

		
    }
    public int Logout(){
    	String urlLogout=null;
    	urlLogout = "http://vozforums.com/login.php?do=logout&"+
    			"logouthash=" + mUser.Token();
    	try {
			res = Jsoup.connect(urlLogout)
						.timeout(60000)
						.method(Method.POST)
						.execute();
			
			mUser.cookies(res.cookies());
			mUser.setLogin(false); 
			return parser();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return -2;
		}
		
    }
    public ArrayList<containPage2> getContain(){
    	return ListContains;
    }
    public containPage2 getContain(int index){
    	return ListContains.get(index);
    }
    public UserInfo mUserInfo(){
    	return mUser;
    }
    public String getIndexPage(){
    	return mIndexPage;
    }
    private void PaserExecute(){
    	
    	Element eleTag1,eleTag1Parent,eleTag1Image ,eleTag1Time ,eleTag1Replies,eleTag1Views ;
		Element eleLogin = doc.select("a[href=private.php]").first();
		parsePage();
		if(eleLogin != null){
			String temp = doc.select("td[class=alt2]").get(0).select("a[href*=mem]").attr("href");
			temp = temp.split("=")[1];
			mUser.setUserId(temp);
		}
		Bitmap bitmap = null;
		String urlImage,text1 = null,text2=null,text3=null,text4=null,text1_url1=null,text2_url2=null;
		Elements eleTag1s = mainElement.select("tr:has(td[id*=td_threads])");
		Elements eleTag2s = mainElement.select("tr > td[class=alt1Active]");
		Iterator<Element> iteTag1 = eleTag1s.iterator();
		Iterator<Element> iteTag2 = eleTag2s.iterator();
		ListContains.add(new containPage2(null,null,null,null,null,null,null));
		if(iteTag2.hasNext())	ListContains.add(new containPage2("Sub-Forum",null,null,null,null,null,null));
		while(iteTag2.hasNext()){
			eleTag1 = iteTag2.next();
			eleTag1Image = eleTag1.select("td > img[id]").first();
			eleTag1Time = eleTag1.nextElementSibling();
			eleTag1Replies = eleTag1Time.nextElementSibling();
			eleTag1Views = eleTag1Replies.nextElementSibling();

			if(eleTag1Image != null){ 
				urlImage= eleTag1Image.select("img").attr("src");
				bitmap = taskLoadImage.DownloadImage(urlImage);
				//bitmap = null;
			}
			if(eleTag1 != null) text1 = eleTag1.text();
			if(eleTag1.select("div > a").first() != null) 
				text1_url1 = eleTag1.select("div > a").first().attr("href");
			if(eleTag1Time.select("span > a").first() != null){
				text2 = eleTag1Time.select("span > a").first().text();
				text2_url2 = eleTag1Time.select("span > a").first().attr("href");
			}
			if(eleTag1Replies != null)		text3 = eleTag1Replies.text();
			if(eleTag1Views != null) text4 = eleTag1Views.text();
			ListContains.add(new containPage2(text1,
					text2, 
					text3,
					text4,
					bitmap,
					text1_url1, 
					text2_url2));
		
		}
		ListContains.add(new containPage2("Thread",null,null,null,null,null,null));
		while(iteTag1.hasNext()){
			eleTag1 = iteTag1.next();
			
			if(eleTag1.select("a[id*=thread_title").first() != null){
				text1 = eleTag1.select("a[id*=thread_title").first().text();
				text1_url1 = eleTag1.select("a[id*=thread_title").first().attr("href");
			}
			if(eleTag1.select("td[class=alt2]:has(span)").first() != null){
				text2 = eleTag1.select("td[class=alt2]:has(span)").first() .text();
			}
			if(eleTag1.select("td[align=center]").first() != null){
				text3 = eleTag1.select("td[align=center]").get(0).text();
				text4 = eleTag1.select("td[align=center]").get(1).text();
			}
			if(eleTag1.select("img[id*=thread_statusicon]").first() != null){
				bitmap = taskLoadImage.DownloadImage(eleTag1.select("img[id*=thread_statusicon]").first().attr("src"));
			}
			if(eleTag1.select("a[id*=thread_gotonew]").first() != null){
				text2_url2 = eleTag1.select("a[id*=thread_gotonew]").first().attr("href");
			}
			ListContains.add(new containPage2(text1,
					text2, 
					text3,
					text4,
					bitmap,
					text1_url1, 
					text2_url2));
			if(eleTag1.hasClass("vozsticky")){
				ListContains.get(ListContains.size()-1).setSticky(true);
			}
		}
		ListContains.add(new containPage2(null,null,null,null,null,null,null));
    }
    private void parsePage(){
    	Element elePage = mainElement.select("div[class=pagenav").first();
    	if(elePage!=null){
    		mIndexPage = elePage.select("td[class=vbmenu_control]").text();
    		curPage = Integer.parseInt(mIndexPage.split(" ")[1]);
    		lastPage = Integer.parseInt(mIndexPage.split(" ")[3]);
    		if(m_url.contains("&page=") != true){
    			m_url = m_url.concat("&page=1");
    		}
    		Urlnext = m_url.substring(0,m_url.length()-1).concat(String.valueOf(curPage+1));
    		
    		Urlprev = m_url.substring(0,m_url.length()-1).concat(String.valueOf(curPage-1));
    		if(Urlprev.contains("&page=0")){
    			Urlprev = Urlprev.split("&page")[0];
    		}
    		Urlfirst = m_url.split("&page")[0];
    		Urllast = Urlfirst.concat("&page=" + String.valueOf(lastPage));
    	}
    }
}
